package com.pinyoumei.app.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.JsonBean;
import com.pinyoumei.app.bean.UserAddressListResponse;
import com.pinyoumei.app.bean.UserAddressSubmitResponse;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.network.HttpMethods;
import com.pinyoumei.app.utils.GetJsonDataUtil;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.dialog.AreaSelectDialog;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import rx.Subscriber;
import vn.luongvo.widget.iosswitchview.SwitchView;

/**
 * 修改（新增）收货地址Activity
 */
public class ModificationAddressActivity extends BaseActivity implements View.OnClickListener {
    private EditText edittext_betteraddress;//详细地址的输入框
    private EditText edittext_recieve_name;//姓名
    private EditText edittext_recieve_phone;//电话
    private TextView text_area_select;//省市区
    private SwitchView switchview;//仿IOS滑动选择器
    private TextView text_delete;//删除收货地址
    private RelativeLayout relative_save;//保存按钮
    private RelativeLayout relative_finish;//返回按钮
    private boolean checked_statue = false;//该地址是否设置为默认地址
    //从地址管理界面传递过来的值
    private String id = "";
    private String recieve_name = "";
    private String recieve_phone = "";
    private String address_area= "";
    private String address_detail = "";
    private String is_default = "";
    private LoadingDailog loadingDailog;
    private AreaSelectDialog areaSelectDialog;//地区选择弹窗
    private ArrayList<String> options1Items = new ArrayList<>();//一级菜单数据
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//二级菜单数据
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//三级菜单数据
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    private static boolean isLoaded = false;
    private String address_province = "";//省
    private String address_city = "";//市
    private String address_county = "";//区

    private boolean isNew = false;
    private rx.Subscriber subscriber;
    private rx.Subscriber subscriber1;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivity_layout_modification);
        initwidget();
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);//进入这个页面就解析json数据
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        if("AddressManagementActivity".equals(getIntent().getAction())){//表明是从地址管理界面列表点击过来的
            id = getIntent().getStringExtra("id");
            recieve_name = getIntent().getStringExtra("recieve_name");
            edittext_recieve_name.setText(recieve_name);
            recieve_phone = getIntent().getStringExtra("recieve_phone");
            edittext_recieve_phone.setText(recieve_phone);
            address_area = getIntent().getStringExtra("address_area");
            text_area_select.setText(address_area);
            text_area_select.setTextColor(Color.parseColor("#000000"));
            address_detail = getIntent().getStringExtra("address_detail");
            edittext_betteraddress.setText(address_detail);
            is_default = getIntent().getStringExtra("is_default");
            if(is_default.equals("1")){//是默认地址
                switchview.setChecked(true);
            }else{
                switchview.setChecked(false);
            }
        }

        if ("ConfirmOrderActivity".equals(getIntent().getAction())){
            isNew = true;
        }

    }
    private void initwidget(){
        switchview = findViewById(R.id.switchview);
        relative_save = findViewById(R.id.relative_save);
        relative_save.setOnClickListener(this);
        relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);
        text_delete = findViewById(R.id.text_delete);
        text_delete.setOnClickListener(this);
        text_area_select = findViewById(R.id.text_area_select);
        text_area_select.setOnClickListener(this);
        edittext_recieve_phone = findViewById(R.id.edittext_recieve_phone);
        edittext_recieve_name = findViewById(R.id.edittext_recieve_name);
        edittext_betteraddress = findViewById(R.id.edittext_betteraddress);
        edittext_betteraddress.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);//设置EditText的显示方式为多行文本输入
        edittext_betteraddress.setGravity(Gravity.TOP);//文本显示的位置在EditText的最上方
        edittext_betteraddress.setSingleLine(false);//改变默认的单行模式
        //水平滚动设置为False
        edittext_betteraddress.setHorizontallyScrolling(false);
        //选择器的状态监听
        switchview.setOnCheckedChangeListener(new SwitchView.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(SwitchView switchView, boolean isChecked){
                checked_statue = isChecked;
            }
        });
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.relative_finish:
                finish();
                break;
            case R.id.text_area_select:
                if(isLoaded){
                    areaSelectDialog.show();
                }
                areaSelectDialog.setOnClickListener(new AreaSelectDialog.DialogClickListener() {
                    @Override
                    public void onClick(String string){
                        //拿到省市区的字符串回调 需要将字符串以"|"进行切割
                        String[] str = string.split(",");
                        address_province = str[0];//表示省
                        address_city = str[1];//市
                        address_county = str[2];//区
                        text_area_select.setText(address_province+address_city+address_county);
                        text_area_select.setTextColor(Color.parseColor("#000000"));
                    }
                });
                break;
            case R.id.relative_save://收货地址保存
                if(TextUtils.isEmpty(edittext_recieve_name.getText().toString())){
                    ToastUtils.showShort("请输入收货人姓名");
                    return;
                }
                if(TextUtils.isEmpty(edittext_recieve_phone.getText().toString())){
                    ToastUtils.showShort("请输入手机号码");
                    return;
                }
                if(TextUtils.isEmpty(text_area_select.getText().toString())){
                    ToastUtils.showShort("请输入省市区地址");
                    return;
                }
                if(TextUtils.isEmpty(edittext_betteraddress.getText().toString())){
                    ToastUtils.showShort("请输入详细地址");
                    return;
                }
                String recieve_name = edittext_recieve_name.getText().toString().trim();
                String recieve_phone = edittext_recieve_phone.getText().toString().trim();
                String address_area = text_area_select.getText().toString().trim();
                String address_detail = edittext_betteraddress.getText().toString().trim();
                String is_default = "0";//1：是默认收货地址 0：不是默认
                if(checked_statue){//默认地址选项打开了
                    is_default ="1";
                }else{
                    is_default ="0";
                }
                //新增收货地址提交
                userAddressSubmit(SPUtils.getAppUserId(this),id,recieve_name,recieve_phone,address_area,address_detail,is_default);
                break;
        }
    }
    //新增收货地址提交
    private void userAddressSubmit(String user_id,String address_id,String recieve_name,String recieve_phone,String address_area,String address_detail,String is_default){
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",user_id);
        map.put("address_id",address_id);
        map.put("recieve_name",recieve_name);
        map.put("recieve_phone",recieve_phone);
        map.put("address_area",address_area);
        map.put("address_detail",address_detail);
        map.put("is_default",is_default);//1：是默认收货地址 0：不是默认
        map.put("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET));
        subscriber = new rx.Subscriber<UserAddressSubmitResponse>(){
            @Override
            public void onStart(){
                super.onStart();
                loadingDailog.show();
            }

            @Override
            public void onCompleted(){

            }

            @Override
            public void onError(Throwable e){
                loadingDailog.dismiss();
            }

            @Override
            public void onNext(UserAddressSubmitResponse userAddressSubmitResponse){
                loadingDailog.dismiss();
                ToastUtils.showShort(userAddressSubmitResponse.getMsg());
                if(userAddressSubmitResponse.getCode()>=0){
                    if (isNew){
                        userAddressList(SPUtils.getAppUserId(mContext));
                    }else {
                        finish();
                    }
                }else{
                    ToastUtils.showShort(userAddressSubmitResponse.getMsg());
                }
            }
        };
        HttpMethods.getInstance().userAddressSubmit(subscriber,map);
    }
    //请求收货地址管理列表
    private void userAddressList(String user_id){
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",user_id);
        map.put("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET));
        subscriber1 = new Subscriber<UserAddressListResponse>() {
            @Override
            public void onStart(){
                super.onStart();
                loadingDailog.show();
            }
            @Override
            public void onCompleted(){

            }
            @Override
            public void onError(Throwable e){
                loadingDailog.dismiss();
            }
            @Override
            public void onNext(UserAddressListResponse userAddressListResponse){
                loadingDailog.dismiss();
                if (userAddressListResponse.getCode() >= 0){
                    Intent intent = new Intent(mContext,ModificationAddressActivity.class);
                    intent.putExtra("id",userAddressListResponse.getResult().getAddress_list().get(0).getId());//地址的id
                    intent.putExtra("recieve_name",userAddressListResponse.getResult().getAddress_list().get(0).getRecieve_name());
                    intent.putExtra("recieve_phone",userAddressListResponse.getResult().getAddress_list().get(0).getRecieve_phone());
                    intent.putExtra("address_area",userAddressListResponse.getResult().getAddress_list().get(0).getAddress_area());
                    intent.putExtra("address_detail",userAddressListResponse.getResult().getAddress_list().get(0).getAddress_detail());
                    intent.putExtra("is_default",userAddressListResponse.getResult().getAddress_list().get(0).getIs_default());
                    intent.setAction("AddressManagementActivity");
                    setResult(2000,intent);
                    finish();
                }else {
                    ToastUtils.showShort(userAddressListResponse.getMsg());
                    finish();
                }
            }
        };
        HttpMethods.getInstance().userAddressList(subscriber1,map);
    }

    //创建一个主线程的Handler用来接收子线程的数据
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case MSG_LOAD_DATA:
                    if (thread == null){//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS: //数据解析完成
                    isLoaded = true;
                    areaSelectDialog = new AreaSelectDialog(ModificationAddressActivity.this,R.layout.dialog_areaselect_layout,new int[]{},options1Items,options2Items,options3Items);
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };
    //解析数据的方法
    private void initJsonData() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            /**
             * 添加省份数据
             */
            options1Items.add(jsonBean.get(i).getPickerViewText());
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
            mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
        }
    }
    //Gson 解析
    public ArrayList<JsonBean> parseData (String result){
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscriber!=null && !subscriber.isUnsubscribed()) {
            subscriber.unsubscribe();
        }

        if (subscriber1!=null && !subscriber1.isUnsubscribed()) {
            subscriber1.unsubscribe();
        }
    }
}
